package servlet;


import com.alibaba.fastjson.JSONArray;
import model.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.*;
import service.impl.*;
import utils.BaseServlet;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@WebServlet("/goods.do")
public class GoodsServlet extends BaseServlet {
    private GoodsService goodsService = new GoodsServiceImpl();
    private CategoryService categoryService = new CategoryServiceImpl();
    private TvService tvService = new TvServiceImpl();
    private PhoneService phoneService = new PhoneServiceImpl();
    private NoteBookService noteBookService = new NoteBookServiceImpl();

    public void upload(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("123");
        try {
            // 1.创建FileItemFactory对象
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            //设置临时目录
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            fileItemFactory.setRepository(repository);

            // 2.创建ServletFileUpload对象
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //设置编码
            servletFileUpload.setHeaderEncoding("UTF-8");

            // 3.解析Form表单提交的所有表单数据
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            // 获取集合的迭代器
            Iterator<FileItem> iter = fileItems.iterator();
            Goods goods = new Goods();
            goods.setState(1);
            goods.setSales(0);
            goods.setCreatetime(new Date());
            // 迭代
            while (iter.hasNext()) {
                // 得到FileItem对象
                FileItem item = iter.next();
                // 判断是普通表单元素
                if (item.isFormField()) {
                    String name = processFormField(item);
                    String value = new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
                    if (name.equals("name")){
                        goods.setName(value);
                        System.out.println(value);
                    }else if (name.equals("description")){
                        goods.setDescription(value);
                    }else if (name.equals("category")){
                        Category category = new Category();
                        category.setId(1);
                        goods.setCategory(category);
                    }else if (name.equals("color")){
                        goods.setColor(value);
                    }else if (name.equals("price")){
                        goods.setPrice(BigDecimal.valueOf(Integer.valueOf(value)));
                    }else if (name.equals("inventory")){
                        goods.setInventory(Integer.valueOf(value));
                    }
                }
                else {
                    String fileName = processUploadedFile(item);
                    goods.setPicture(fileName);
                    System.out.println(fileName);
                }
            }
            goodsService.addGoods(goods);

        } catch (FileUploadException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private String processUploadedFile(FileItem item){
        String fileName = "";
        try {
            // 获取文件名
            fileName = item.getName();
            //修改文件名
            fileName = UUID.randomUUID()+fileName;
            // 上传文件保存的路径
            String realPath = getServletContext().getRealPath("/uploads/");
            // 根据文件名创建文件
            File file = new File(realPath + fileName);
            // 写入文件
            item.write(file);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }
    private String processFormField(FileItem item) {
        String fieldName = item.getFieldName();
        return fieldName;
    }


    /**
     * 添加笔记本参数
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addNotebook(HttpServletRequest req, HttpServletResponse resp)throws IOException{
        //先执行添加商品基础参数方法
        addGoods(req,resp);
        String notebookscreensize = req.getParameter("notebookscreensize");
        String cpu = req.getParameter("cpu");
        String notebookseries = req.getParameter("notebookseries");
        String notebookthickness = req.getParameter("notebookthickness");
        String harddisk = req.getParameter("harddisk");
        String notebookmemory = req.getParameter("notebookmemory");
        String notebookscreenresolution = req.getParameter("notebookscreenresolution");
        String standbytime = req.getParameter("standbytime");
        String weight = req.getParameter("weight");
        String extensiondisk=req.getParameter("extensiondisk");

        NoteBook noteBook = new NoteBook();
        noteBook.setGoods_id(goodsService.findLastGoods());
        noteBook.setCpu(cpu);
        noteBook.setExtension_disk(extensiondisk);
        noteBook.setScreen_resolution(notebookscreenresolution);
        noteBook.setHard_disk(harddisk);
        noteBook.setSeries(notebookseries);
        noteBook.setMemory(notebookmemory);
        noteBook.setThickness(notebookthickness);
        noteBook.setWeight(weight);
        noteBook.setStandbytime(standbytime);
        noteBook.setScreenre_size(notebookscreensize);

        boolean isAdd = noteBookService.add(noteBook);
        PrintWriter out = resp.getWriter();
        if (isAdd){
            out.write("true");
        }else{
            out.write("false");
        }
        out.close();
    }
    /**
     * 添加电视参数
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addTv(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        //先执行添加商品基础参数方法
        addGoods(req,resp);
        String tvscreensize =req.getParameter("tvscreensize");
        String tvseries =req.getParameter("tvseries");
        String remote =req.getParameter("remote");
        String border =req.getParameter("border");
        String tvscreenresolution =req.getParameter("tvscreenresolution");
        String usb =req.getParameter("usb");

        Tv tv = new Tv();
        //手机的商品编号绑定为最新添加的商品
        tv.setGoods_id(goodsService.findLastGoods());
        tv.setBorder(border);
        tv.setRemote(remote);
        tv.setScreen_resolution(tvscreenresolution);
        tv.setScreenre_size(tvscreensize);
        tv.setSeries(tvseries);
        tv.setUsb(usb);

        boolean isAdd = tvService.add(tv);
        PrintWriter out = resp.getWriter();
        if (isAdd){
            out.write("true");
        }else{
            out.write("false");
        }
        out.close();
    }

    /**
     * 添加手机参数方法
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addPhone(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //先执行添加商品基础参数
        addGoods(req,resp);
        String phonescreensize = req.getParameter("phonescreensize");
        String pixel = req.getParameter("pixel");
        String phonememory = req.getParameter("phonememory");
        String batterylife = req.getParameter("batterylife");
        String cpumodel = req.getParameter("cpumodel");
        String cpufrequency = req.getParameter("cpufrequency");
        String frontcamera = req.getParameter("frontcamera");
        String phonescreenresolution = req.getParameter("phonescreenresolution");
        String capacity = req.getParameter("capacity");
        String phonethickness = req.getParameter("phonethickness");
        String networktype = req.getParameter("networktype");
        String networkmodel = req.getParameter("networkmodel");

        Phone phone = new Phone();
        //手机的商品编号绑定为最新添加的商品
        phone.setGoods_id(goodsService.findLastGoods());
        phone.setScreen_size(phonescreensize);
        phone.setPixel(pixel);
        phone.setMemory(phonememory);
        phone.setBattery_life(batterylife);
        phone.setCpu_model(cpumodel);
        phone.setCpu_frequency(cpufrequency);
        phone.setFront_camera(frontcamera);
        phone.setScreenre_solution(phonescreenresolution);
        phone.setCapacity(capacity);
        phone.setThickness(phonethickness);
        phone.setNetwork_type(networktype);
        phone.setNetwork_model(networkmodel);

        //获取输出流
        PrintWriter out = resp.getWriter();
        boolean isAdd =phoneService.add(phone);
        if (isAdd){
            out.write("true");
        }else{
            out.write("false");
        }
        out.close();

    }

    /**
     * 添加基础参数方法
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String categoryId = req.getParameter("category");
        String color = req.getParameter("color");
        String price = req.getParameter("price");
        String picture = req.getParameter("picture");
        String inventory = req.getParameter("inventory");
        String description = req.getParameter("description");

        System.out.println(price);

        Goods goods = new Goods();
        goods.setName(name);
        goods.setColor(color);
        goods.setCreatetime(new Date());
        goods.setPrice(BigDecimal.valueOf(Integer.valueOf(price)));
        goods.setPicture("../images/phone.jpg");
        goods.setSales(0);
        goods.setState(1);
        goods.setInventory(Integer.valueOf(inventory));
        goods.setDescription(description);
        Category category = new Category();
        category.setId(Integer.valueOf(categoryId));
        goods.setCategory(category);

        boolean isAdd = goodsService.addGoods(goods);
        PrintWriter out = resp.getWriter();
        if (isAdd){
            out.write("true");
        }else{
            out.write("false");
        }
        out.close();
    }

    /**
     * 列出所有分类方法
     * @param req
     * @param resp
     * @throws IOException
     */
    public void listCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Category> categories = categoryService.findAll();
        req.getSession().setAttribute("categories",categories);
        //将集合转换为JSON字符串
        String jsonArrayString = JSONArray.toJSONString(categories);
//        System.out.println(jsonArrayString);
        resp.setContentType("application/json;charset=UTF-8");
        //获取输出流
        PrintWriter out = resp.getWriter();
        //输出
        out.write(jsonArrayString);
        //关闭流
        out.close();
    }

    /**
     * 删除商品
     * @param req
     * @param resp
     * @throws IOException
     */
    public void deleteGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String goodsId = req.getParameter("goodsId");

        Boolean isDel = goodsService.delGoods(Integer.valueOf(goodsId));
        PrintWriter out = resp.getWriter();
        if (isDel){
            out.write("true");
        }else{
            out.write("false");
        }
        out.close();
    }

    /**
     * 列出所有商品方法
     * @param req
     * @param resp
     * @throws IOException
     */
    public void listGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Goods> goods = goodsService.findAll();
        req.getSession().setAttribute("goods",goods);
        //将集合转换为JSON字符串
        String jsonArrayString = JSONArray.toJSONString(goods);
        //将字符口中输出
//        System.out.println(jsonArrayString);
        resp.setContentType("application/json;charset=UTF-8");
        //获取输出流
        PrintWriter out = resp.getWriter();
        //输出
        out.write(jsonArrayString);
        //关闭流
        out.close();
    }

    /**
     * 前端首页模糊查询
     * @param req
     * @param resp
     * @throws IOException
     */
    public void searchByName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        StringBuffer keyword = new StringBuffer(req.getParameter("keyword"));
        //在获得的字符串前加 %
        keyword.insert(0,"%");
        //在获得的字符串后加 %   实现模糊查询
        keyword.append("%");
        List<Goods> goods = goodsService.searchByName(keyword.toString());
        req.getSession().setAttribute("goods",goods);
        //将集合转换为JSON字符串
        String jsonArrayString = JSONArray.toJSONString(goods);
        //将字符口中输出
        resp.setContentType("application/json;charset=UTF-8");
        //获取输出流
        PrintWriter out = resp.getWriter();
        //输出
        out.write(jsonArrayString);
        //关闭流
        out.close();
    }

    /**
     * 后端模糊查询
     * @param req
     * @param resp
     * @throws IOException
     */
    public void searchGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        StringBuffer keyword = new StringBuffer(req.getParameter("keyword"));
        //在获得的字符串前加 %
        keyword.insert(0,"%");
        //在获得的字符串后加 %   实现模糊查询
        keyword.append("%");
        String category = req.getParameter("category");
        String state = req.getParameter("state");
        List<Goods> goods = goodsService.search(keyword.toString(),Integer.valueOf(category),Integer.valueOf(state));
        req.getSession().setAttribute("goods",goods);
        //将集合转换为JSON字符串
        String jsonArrayString = JSONArray.toJSONString(goods);
        //将字符口中输出
        resp.setContentType("application/json;charset=UTF-8");
        //获取输出流
        PrintWriter out = resp.getWriter();
        //输出
        out.write(jsonArrayString);
        //关闭流
        out.close();
    }

    /**
     * 根据id查找商品
     * @param req
     * @param resp
     * @throws IOException
     */
    public void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        //获取id
        String Id = req.getParameter("id");
        //将id转换为integer
        Integer id = Integer.parseInt(Id);
        //通过id查找
        Goods goods = goodsService.findById(id);
        //设置返回前端数据格式
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //将goods转换为json数据格式
        String jsonString = JSONArray.toJSONString(goods);
        System.out.println(jsonString);
        out.write(jsonString);
        //关闭流
        out.close();
    }
}
